package Dom4j;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Dom4jDemo1 {
    @Test
    public void parseXMLData() throws Exception {
        //1.创建Dom4j解析器对象，代表整个dom4j框架
        SAXReader saxReader = new SAXReader();
        //2.把XML文件加载到内存中成为一个Document文档对象
//        System.out.println(
//                Dom4jDemo1.class.getClassLoader().getResource("Contacts.xml")
//        );
        Document document = saxReader.read(Dom4jDemo1.class.getClassLoader().getResource("Contacts.xml"));
        Element root=document.getRootElement();
        System.out.println(root.getName());


    }

    public static void main(String[] args) throws Exception {
        //1.创建Dom4j解析器对象，代表整个dom4j框架
        SAXReader saxReader = new SAXReader();
        //2.把XML文件加载到内存中成为一个Document文档对象
//        Document document = saxReader.read(new File("JavaSE\\src\\Dom4j\\Contacts.xml"));
        //getResourceAsStream 直接去src下寻找文件
        Document document = null;
        try (  InputStream is=Dom4jDemo1.class.getResourceAsStream("/Contacts.xml")){
            document = saxReader.read(is);
            Element root=document.getRootElement();
            Element contact = root.element("contact");
            Element email = contact.element("email");
            String text = email.getText();
            String name = contact.elementText("name");
            Attribute id = contact.attribute("id");
            System.out.println(root.getName());
            List<Element> elements = root.elements();
            for (Element element : elements) {
                System.out.println(element.getName());
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
}
